<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2 class="login-title">项目管理双周报系统登录</h2>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onLogin" :loading="loading" style="width:100%">登录</el-button>
        </el-form-item>
        <el-form-item v-if="error">
          <el-alert :title="error" type="error" show-icon />
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { getUserList, getUserProjects,login} from '../api/user'
import { verifyPassword } from '../utils/crypto'
import { api } from '../utils/apiWrapper.js'
import apiConfig from '../utils/apiConfig.js'
const router = useRouter()
const formRef = ref()
const form = ref({ username: '', password: '' })
const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}
const loading = ref(false)
const error = ref('')

const onLogin = async () => {
  error.value = ''
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    loading.value = true
    try {
      // 1) 调用后端登录，获取 token（后端同时校验用户名密码）
      console.log(form.value);
      const loginRes = await login({ username: form.value.username, password: form.value.password })
      if (!loginRes || !loginRes.token) {
        throw new Error('登录失败，未返回token')
      }
      
      // 保存token和用户信息
      localStorage.setItem('token', loginRes.token)
      localStorage.setItem('user', JSON.stringify(loginRes.user))
      await apiConfig.init()
      localStorage.setItem('apiBaseURL', apiConfig.baseURL)
      console.log('登录成功，token已保存:', loginRes.token);
      console.log('用户信息已保存:', loginRes.user);

      // 等待一下确保localStorage更新
      await new Promise(resolve => setTimeout(resolve, 100));

      // 获取用户项目信息
      const projectRes = await getUserProjects(loginRes.user.id)
      console.log('获取到的项目信息:', projectRes);

      localStorage.setItem('userProject', JSON.stringify(projectRes))
      ElMessage.success('登录成功')
      router.push('/')
    } catch (e) {
      error.value = e?.message || '登录失败，请检查网络或接口服务'
    } finally {
      loading.value = false
    }
  })
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(120deg, #409EFF 0%, #66b1ff 100%);
}
.login-card {
  width: 380px;
  padding: 40px 30px 20px 30px;
  border-radius: 12px;
  box-shadow: 0 4px 24px rgba(0,0,0,0.08);
}
.login-title {
  text-align: center;
  margin-bottom: 30px;
  color: #409EFF;
  font-weight: bold;
  font-size: 22px;
  letter-spacing: 2px;
}
</style> 